/*********************************************************************************
CREATED BY: SCOTT FIELDER 
CREATED DATE: 4/18/2011


REVISION HISTORY:
-

***********************************************************************************/





global with sharing class FB_Auth {
     
	public String FBcookie {get; set;}
	public String FBPermissions {get; set;}
	public Boolean FBDevMode {get; set;}
	public String FBAppId {get; set;}
	public String ApexCookieDelim {get; set;}
	public String authCode {get; set;}
	public String endpoint {get; set;}
	public String redirectURL {get; set;}
	public string accessToken {get; set;}
	public string meResponse {get; set;}
	public Map<string, string> fbRespMap = new Map<string, string>();
	public boolean isAuth {get; set;}
	
	public FB_Auth(){
		FBPermissions = FB_Graph_Settings__c.getInstance().FB_Permissions_Requested__c;
		FBAppId = FB_Graph_Settings__c.getInstance().FB_App_Id__c;
		
	}
	
	public void doFBAuth(){
		
		try{
			FBPermissions = FB_Graph_Settings__c.getInstance().FB_Permissions_Requested__c;
		    FBDevMode = FB_Graph_Settings__c.getInstance().Development_Mode__c;
		    FBAppId = FB_Graph_Settings__c.getInstance().FB_App_Id__c;
			ApexCookieDelim = Apex_Cookie_Delimeter__c.getInstance().Delimeter_Character__c;
			
			redirectURL = Site.getCurrentSiteUrl();
			authCode = ApexPages.currentPage().getParameters().get('code');
			system.debug('************authcode: ' + authCode);
			
			Cookie authCookie = UTIL_Cookie.retrieveCookie();
		     
		    if(authCode != null && authCookie == null){
		    	FB_AccessToken cls = new FB_AccessToken();
				endpoint = cls.doFBAuthToken(redirectURL, authCode);
				FB_Graph fbGraph = new FB_Graph(); 
				
				//TO ENSURE TEST COVERAGE
				if(FBDevMode == true){
					accessToken = 'access_token=170909779623787&#124;add081be8cee79498deb83e2-1070072033&#124;rbxxO_e6jLX2WPH2qxDAxG0BoP8';
				}else{
					accessToken = fbGraph.doCallout(endpoint);
				}
				
				if(accessToken != null){
					List<string> aTokenList = accessToken.split('=', 0);
					if(!aTokenList.isEmpty()){
						FB_Me fbm = new FB_Me();
						string meEndpoint = fbm.doFBMe(aTokenList[1]); 
						if(meEndpoint != null){
							FB_JSON fbjson = new FB_JSON();
							//TO ENSURE TEST COVERAGE
							if(FBDevMode == true){
								meResponse =  fbjson.testJSON();
							}else{
								meResponse = fbGraph.doCallout(meEndpoint);
							}
							
							if(meResponse != null){
								fbRespMap = fbjson.parseFB_JSON(meResponse);
								if(!fbRespMap.isEmpty()){
									FB_PersonAccount fbpa = new FB_PersonAccount();
									fbpa.managePerson(fbRespMap); 
								}
							}
						}
						 
						
						system.debug('***************aTokenList: ' + aTokenList);
						
						authCookie = new Cookie(FB_Cookie_Name__c.getInstance().Name__c, UTIL_encryption.encryptStr(fbRespMap.get('id') + ApexCookieDelim + aTokenList[1]), null, -1, false);
			    		ApexPages.currentPage().setCookies(new Cookie[]{authCookie});
					}
				}
				
			}
			
			system.debug('*********redirectURL: ' + redirectURL);
			system.debug('*********endpoint: ' + endpoint);
			system.debug('*********fbRespMap: ' + fbRespMap);
			system.debug('*********authCookie: ' + authCookie);
			
		}catch(exception e){
			
		}
		
	}
	
	
	
		
	
	/***********************************************************
	* 						TEST METHODS
	***********************************************************/
	
	static testMethod void test_doAuth(){
		
		test.startTest(); 
		
		FB_Graph_Settings__c fb = FB_Graph_Settings__c.getInstance();
		
		if(fb == null) {
            fb = new FB_Graph_Settings__c(SetupOwnerId = UserInfo.getOrganizationId());
        }
        
        fb.OF__API_Key__c = '1111111111111111111111111';
        fb.OF__App_Secret__c = '11111111111111111111111111111';
        fb.OF__Development_Mode__c = true;
        fb.OF__FB_App_Id__c = '11111111111111111111111';
        fb.OF__FB_Permissions_Requested__c = 'email,read_stream,publish_stream,offline_access,user_birthday';
        fb.OF__Graph_Endpoint__c = 'https://graph.facebook.com/';
        fb.OF__Host_Header__c = 'graph.facebook.com';
        
        Database.upsert(fb);
		
		
		Apex_Cookie_Delimeter__c ad = Apex_Cookie_Delimeter__c.getInstance();
		if(ad == null) {
            ad = new Apex_Cookie_Delimeter__c(SetupOwnerId = UserInfo.getOrganizationId());
        }
		
		ad.Delimeter_Character__c ='--';
		Database.upsert(ad);
		
		
		FB_Auth cls = new FB_Auth();
		
		PageReference pgRef = Page.Index;
		test.setCurrentPage(pgRef);
		
		ApexPages.currentPage().getParameters().put('code', '1234');
		
		cls.doFBAuth();
		
		test.stopTest();
		
		
	}
	
	
	
	
	
	
	
	
	
	
	
}